import { Input, message } from "antd";
import axios from "axios";
import { useEffect, useState } from "react";
import { ITodo } from "./dto";
import styles from "./index.module.less";
import TodoCard from "./todo-card";

const TodoListPage = () => {
  const [todos, setTodos] = useState<ITodo[]>([]);
  const [todoTitle, setTodoTitle] = useState<string>();
  const [showFinished, setShowFinished] = useState<boolean>(false);
  const getAllTodos = () => {
    axios.get("/todos").then(({ data: res }: { data: { data: ITodo[] } }) => {
      setTodos(res.data);
    });
  };
  const addTodoItem = () => {
    if (todoTitle === undefined) {
      return message.error("请输入Todo内容！！！");
    } else {
      axios
        .post("/todos/todo", { title: todoTitle })
        .then(({ data: res }: { data: { data: ITodo[] } }) => {
          if (res.data) {
            setTodoTitle(undefined);
            getAllTodos();
          }
        });
    }
  };
  useEffect(() => {
    getAllTodos();
  }, []);
  return (
    <div className={styles.container}>
      <div className={styles.todoList}>
        <div className={styles.operation}>
          <span className={`${styles.add}`}>
            <Input
              value={todoTitle}
              placeholder="请输入"
              maxLength={50}
              onChange={(e) => setTodoTitle(e.target.value)}
            />
            <span>
              <span onClick={() => addTodoItem()} style={{ cursor: "pointer" }}>
                Add
              </span>
            </span>
          </span>
          <span
            className={`${styles.filterBtn} ${
              showFinished ? styles.active : ""
            }`}
            onClick={() => setShowFinished(!showFinished)}
          >
            <span>Show</span>
            <span>
              <span>Finished</span>
            </span>
          </span>
        </div>
        <div>
          {todos &&
            todos.map((todo) => {
              return showFinished ? (
                <TodoCard todo={todo} key={todo.id} getAllTodos={getAllTodos} />
              ) : todo.is_finished ? (
                false
              ) : (
                <TodoCard todo={todo} key={todo.id} getAllTodos={getAllTodos} />
              );
            })}
        </div>
      </div>
      <div className={styles.addTodo}>
        <div></div>
      </div>
    </div>
  );
};

export default TodoListPage;
